package com.demo.zhou.sniper.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;


import com.demo.zhou.sniper.R;
import com.demo.zhou.sniper.adapter.ZuArrayAdapter;
import com.demo.zhou.sniper.application.MyApplication;
import com.demo.zhou.sniper.gen.BiaoqianDao;
import com.demo.zhou.sniper.gen.DaoSession;
import com.demo.zhou.sniper.module.Biaoqian;

import java.util.ArrayList;
import java.util.List;

public class ChaxunActivity extends BaseActivity {

    private ListView chaxun_lv_list;
    private EditText mSearchView;
    private ImageView mClearBtn;
    private Spinner mBLSelector; //选择B L 类型

    String searchKey = "";
    String blKey = "";

    DaoSession daoSession;
    BiaoqianDao biaoqianDao;
    private List<Biaoqian> bqAll = new ArrayList<>();
    private List<String> bqLabelAll = new ArrayList<>();
    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("查询");
        chaxun_lv_list = (ListView) findViewById(R.id.chaxun_lv_list);
        mSearchView = (EditText) findViewById(R.id.search_edit);
        mClearBtn = (ImageView) findViewById(R.id.ib_searchtext_delete);
        mBLSelector = (Spinner) findViewById(R.id.blSelector);
        daoSession = ((MyApplication) getApplication()).getDaoSession();
        biaoqianDao = daoSession.getBiaoqianDao();
        bqAll = biaoqianDao.loadAll();
        bqLabelAll = queryBiaoqian(bqAll);
        adapter = new ZuArrayAdapter(this,
                R.layout.item_allqun_list,
                R.id.tv_item,
                bqLabelAll);
        chaxun_lv_list.setAdapter(adapter);

        // b l 选择
        final List<String> blData = new ArrayList<>();
        blData.add("全部");
        blData.add("B");
        blData.add("L");

        ArrayAdapter<String> starAdapter = new ArrayAdapter<String>(this, R.layout.sniper_text_select_item, blData);
        starAdapter.setDropDownViewResource(R.layout.sniper_text_normal_item);
        mBLSelector.setAdapter(starAdapter);
        mBLSelector.setSelection(0, true);
        mBLSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //群数据处理
                if (position > 0) {
                    blKey = blData.get(position).toLowerCase();
                } else {
                    blKey = "";
                }
                // 查询数据库
                bqAll = biaoqianDao.loadAll();
                bqLabelAll.clear();
                bqLabelAll.addAll(queryByBiaoqian(bqAll, searchKey, blKey));
                Log.e("sniper", "搜索结果标签总数：" + bqLabelAll.size());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
        onClick();
    }

    public void onClick() {
        chaxun_lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ChaxunActivity.this, SetDetailsActivity.class);
                Biaoqian bq = bqAll.get(position);
                intent.putExtra("primitives", bq.getPrimitives());
                String mode = bq.getLabel().charAt(bq.getLabel().length() - 1) + "";
                intent.putExtra("mode", mode);
                startActivity(intent);
                finish();
            }
        });
        // 添加长按点击,得到点中的index，即参数arg2
        chaxun_lv_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                           final int arg2, long arg3) {
                //定义AlertDialog.Builder对象，当长按列表项的时候弹出确认删除对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(ChaxunActivity.this);
                builder.setMessage("确定删除?");
                builder.setTitle("提示");

                //添加AlertDialog.Builder对象的setPositiveButton()方法
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (bqLabelAll.remove(arg2) != null) {
                            System.out.println("success");
                        } else {
                            System.out.println("failed");
                        }
                        adapter.notifyDataSetChanged();
                        deleteData(bqAll.get(arg2).getId());
                        Toast.makeText(ChaxunActivity.this, "删除成功！", Toast.LENGTH_SHORT).show();
                    }
                });

                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builder.create().show();
                return true;
            }
        });

        mSearchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable == null) {
                    searchKey = "";
                    mClearBtn.setVisibility(View.GONE);
                } else {

                    if (editable.toString().length() < 1) {
                        mClearBtn.setVisibility(View.GONE);
                        // 查询数据库
                        bqAll = biaoqianDao.loadAll();
                        bqLabelAll.clear();
                        bqLabelAll.addAll(queryBiaoqian(bqAll));
                    } else {

                        mClearBtn.setVisibility(View.VISIBLE);
                        searchKey = editable.toString().trim();
                        // 查询数据库
                        bqAll = biaoqianDao.loadAll();
                        bqLabelAll.clear();
                        bqLabelAll.addAll(queryByBiaoqian(bqAll, searchKey, blKey));
                    }
                    Log.e("sniper", "搜索结果标签总数：" + bqLabelAll.size());
                    adapter.notifyDataSetChanged();
                }


            }
        });
        mClearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSearchView.setText("");
            }
        });
    }

    private List<String> queryByBiaoqian(List<Biaoqian> bqAll, String key, String blKey) {
        List<String> bqLabels = new ArrayList<>();
        for (Biaoqian bq : bqAll) {
            // 兼容小写字母
            if (bq.getLabel().toLowerCase().contains(key) && bq.getLabel().toLowerCase().contains(blKey)) {
                bqLabels.add(splitAlpha(bq.getLabel()));
                Log.e("sniper", "符合搜索条件的标签：" + bq.getLabel());
            }
        }
        return bqLabels;
    }

    private List<String> queryBiaoqian(List<Biaoqian> bqAll) {
        List<String> bqLabels = new ArrayList<>();
        for (Biaoqian bq : bqAll) {
            bqLabels.add(splitAlpha(bq.getLabel()));
        }
        return bqLabels;
    }

    public void deleteData(Long index) {
        biaoqianDao.deleteByKey(index);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_chaxun;
    }

    /**
     * 判断是否是字母
     * @param str 传入字符串
     * @return 是字母返回true，否则返回false
     */

    public boolean isAlpha(String str) {

        if(str==null) return false;

        return str.matches("[a-zA-Z]+");

    }

    private String splitAlpha(String str) {
        String label = str;
        String alpha = label.substring(label.length() - 1);
        Log.e("sniper", "字母：" + alpha);
        if (isAlpha(alpha)) {
            label = label.substring(0, label.length() - 1) + " " + alpha;
        }
        return label;
    }
}
